import React, { useRef, useState, useCallback, useEffect } from 'react';
import { ArrowDown, CheckCircle, Circle } from 'lucide-react';
import { Markdown } from '@/components/ui/markdown';
import { UnifiedMessage } from '@/components/thread/types';
import { RonqiLogo } from '@/components/sidebar/ronqi-logo';
import { safeJsonParse } from '@/components/thread/utils';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils'; // 请确保你有 cn 工具函数
import { useMediaQuery } from '@/hooks/use-media-query'; // 是否需要根据你的项目结构调整

export interface SupportChatContentProps {
  messages: UnifiedMessage[];
  readOnly?: boolean;
  agentName?: string;
  agentAvatar?: React.ReactNode;
  emptyStateComponent?: React.ReactNode;
}

export const SupportChatContent: React.FC<SupportChatContentProps> = ({
  messages,
  readOnly = false,
  agentName = 'Suna',
  agentAvatar = <RonqiLogo size={16} />,
  emptyStateComponent,
}) => {
  const isMobile = useMediaQuery('(max-width: 640px)');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messagesContainerRef = useRef<HTMLDivElement>(null);
  const [showScrollButton, setShowScrollButton] = useState(false);
  const [, setUserHasScrolled] = useState(false);

  const containerClassName =
    'flex-1 overflow-y-auto scrollbar-thin scrollbar-track-secondary/0 scrollbar-thumb-primary/10 scrollbar-thumb-rounded-full hover:scrollbar-thumb-primary/10 px-6 py-4 pb-72 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60';

  const handleScroll = () => {
    if (!messagesContainerRef.current) return;
    const { scrollTop, scrollHeight, clientHeight } =
      messagesContainerRef.current;
    const isScrolledUp = scrollHeight - scrollTop - clientHeight > 100;
    setShowScrollButton(isScrolledUp);
    setUserHasScrolled(isScrolledUp);
  };

  const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => {
    messagesEndRef.current?.scrollIntoView({ behavior });
  }, []);

  const renderMessages = () => {
    type MessageGroup = {
      type: 'user' | 'assistant_group';
      messages: UnifiedMessage[];
      key: string;
    };

    const groupedMessages: MessageGroup[] = [];
    let currentGroup: MessageGroup | null = null;
    let assistantGroupCounter = 0;

    messages.forEach((message, index) => {
      const messageType = message.type;
      const key = message.message_id || `msg-${index}`;

      if (messageType === 'user') {
        if (currentGroup) {
          groupedMessages.push(currentGroup);
          currentGroup = null;
        }
        groupedMessages.push({ type: 'user', messages: [message], key });
      } else if (messageType === 'assistant') {
        const canAddToExistingGroup =
          currentGroup && currentGroup.type === 'assistant_group';

        if (canAddToExistingGroup) {
          currentGroup?.messages.push(message);
        } else {
          if (currentGroup) {
            groupedMessages.push(currentGroup);
          }
          assistantGroupCounter++;
          currentGroup = {
            type: 'assistant_group',
            messages: [message],
            key: `assistant-group-${assistantGroupCounter}`,
          };
        }
      }
    });

    if (currentGroup) {
      groupedMessages.push(currentGroup);
    }

    return groupedMessages.map((group) => {
      if (group.type === 'user') {
        const message = group.messages[0];
        const messageContent =
          typeof message.content === 'string' ? message.content : '';

        return (
          <div key={group.key} className="flex justify-end">
            <div className="flex max-w-[85%] rounded-3xl rounded-br-lg bg-card border px-4 py-3 break-words overflow-hidden">
              <div className="space-y-3 min-w-0 flex-1">
                <Markdown className="text-sm prose prose-sm dark:prose-invert chat-markdown max-w-none [&>:first-child]:mt-0 prose-headings:mt-3 break-words overflow-wrap-anywhere">
                  {messageContent}
                </Markdown>
              </div>
            </div>
          </div>
        );
      } else if (group.type === 'assistant_group') {
        return (
          <div key={group.key}>
            <div className="flex flex-col gap-2">
              <div className="flex items-center">
                <div className="rounded-md flex items-center justify-center">
                  {agentAvatar}
                </div>
                <p className="ml-2 text-sm text-muted-foreground">
                  {agentName}
                </p>
              </div>
              <div className="flex max-w-[90%] text-sm break-words overflow-hidden">
                <div className="space-y-2 min-w-0 flex-1">
                  {group.messages.map((message, msgIndex) => {
                    if (message.type === 'assistant') {
                      const msgKey =
                        message.message_id || `submsg-assistant-${msgIndex}`;
                      const parsedContent = safeJsonParse<any>(
                        message.content,
                        {
                          content: message.content,
                        },
                      );
                      const content = parsedContent.content || message.content;

                      return (
                        <div
                          key={msgKey}
                          className={msgIndex > 0 ? 'mt-4' : ''}
                        >
                          <div className="prose prose-sm dark:prose-invert chat-markdown max-w-none [&>:first-child]:mt-0 prose-headings:mt-3 break-words overflow-hidden">
                            <Markdown className="text-sm">{content}</Markdown>
                          </div>
                        </div>
                      );
                    }
                    return null;
                  })}
                </div>
              </div>
            </div>
          </div>
        );
      }
      return null;
    });
  };

  // todolist mock
  interface TodoItem {
    id: number;
    title: string;
    completed: boolean;
  }
  const [todoList, setTodoList] = useState<TodoItem[]>([]);

  // 模拟接口请求
  useEffect(() => {
    const mockData: TodoItem[] = [
      { id: 1, title: '完成接口联调', completed: false },
      { id: 2, title: '补充文档说明', completed: true },
      { id: 3, title: '优化异常处理', completed: false },
      { id: 4, title: '设计任务卡片样式', completed: true },
      { id: 5, title: '设计任务卡片样式', completed: true },
      { id: 6, title: '设计任务卡片样式', completed: true },
      { id: 7, title: '设计任务卡片样式', completed: true },
      { id: 8, title: '设计任务卡片样式', completed: true },
      { id: 9, title: '设计任务卡片样式', completed: true },
    ];
    setTimeout(() => setTodoList(mockData), 500); // 模拟延迟
  }, []);
  return (
    <div className="fixed right-6 top-1/2 -translate-y-1/2 z-30 pointer-events-auto">
      <div
        className={cn(
          'border rounded-2xl flex flex-col shadow-2xl bg-background h-[92vh] overflow-hidden',
          isMobile
            ? 'w-full max-w-[90vw]'
            : 'w-[90vw] sm:w-[450px] md:w-[500px] lg:w-[550px] xl:w-[650px]',
        )}
      >
        {/* Summary Section */}
        <div className="h-[25%] flex border-b px-4 py-3 bg-muted/50 rounded-t-2xl">
          {/* 左侧 聊天记录总结 */}
          <div className="w-1/2 flex flex-col pr-4">
            <div className="flex items-center justify-between mb-1 h-6">
              <h3 className="text-sm font-medium text-zinc-800 dark:text-zinc-200 leading-6">
                聊天记录总结
              </h3>
              <Button
                variant="ghost"
                size="sm"
                className="text-sm leading-6"
                onClick={() => console.log('生成总结')}
              >
                生成总结
              </Button>
            </div>

            {/* 内容区域占满剩余空间 */}
            <div className="flex-1 overflow-auto text-sm text-zinc-600 dark:text-zinc-400 leading-relaxed">
              <div className="pr-1">
                <p>
                  这里将显示聊天记录的自动总结...这里将显示聊天记录的自动总结...
                  这里将显示聊天记录的自动总结...这里将显示聊天记录的自动总结...
                  这里将显示聊天记录的自动总结...这里将显示聊天记录的自动总结...
                  这里将显示聊天记录的自动总结...这里将显示聊天记录的自动总结...
                  这里将显示聊天记录的自动总结...这里将显示聊天记录的自动总结...
                  这里将显示聊天记录的自动总结...这里将显示聊天记录的自动总结...
                </p>
              </div>
            </div>
          </div>

          {/* 中间分割线 */}
          <div className="w-px bg-zinc-300 dark:bg-zinc-700 " />

          {/* 右侧 ToDoList */}
          <div className="w-1/2 flex flex-col pl-4">
            <div className="mb-1 h-6 flex items-center">
              <h3 className="text-sm font-medium text-zinc-800 dark:text-zinc-200 leading-6">
                任务清单
              </h3>
              {/* 这里加个空div撑开和左侧按钮区域宽度一致 */}
              <div className="ml-auto w-[72px]" />
            </div>
            <ul className="flex-1 text-sm text-zinc-700 dark:text-zinc-400 space-y-1 overflow-auto leading-snug">
              {todoList.length > 0 ? (
                todoList.map((item) => (
                  <li key={item.id} className="flex items-center space-x-2">
                    {item.completed ? (
                      <CheckCircle className="w-4 h-4 text-green-500" />
                    ) : (
                      <Circle className="w-4 h-4 text-zinc-400" />
                    )}
                    <span
                      className={
                        item.completed
                          ? 'text-zinc-400 line-through'
                          : 'text-zinc-800 dark:text-zinc-100'
                      }
                    >
                      {item.title}
                    </span>
                  </li>
                ))
              ) : (
                <li className="text-zinc-500 text-sm">加载中...</li>
              )}
            </ul>
          </div>
        </div>
        {/* Chat Messages */}
        <div className="h-[75%] overflow-hidden relative">
          {messages.length === 0 ? (
            <div className="flex-1 min-h-[60vh] flex items-center justify-center px-6">
              {emptyStateComponent || (
                <div className="text-center text-muted-foreground">
                  {readOnly ? '暂无消息显示。' : '发送消息开始对话。'}
                </div>
              )}
            </div>
          ) : (
            <div
              ref={messagesContainerRef}
              className={containerClassName}
              onScroll={handleScroll}
            >
              <div className="mx-auto max-w-3xl md:px-8 min-w-0">
                <div className="space-y-8 min-w-0">
                  {renderMessages()}
                  <div ref={messagesEndRef} className="h-1" />
                </div>
              </div>
            </div>
          )}

          {showScrollButton && (
            <button
              className="absolute bottom-4 right-4 z-10 h-8 w-8 rounded-full shadow-md bg-primary text-white"
              onClick={() => scrollToBottom('smooth')}
            >
              <ArrowDown className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default SupportChatContent;
